package com.three.crm.page.feedback;


import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.DragEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.lxj.xpopup.XPopup;
import com.three.crm.R;
import com.three.crm.adapter.NinePictureAdapter;
import com.three.crm.base.BaseActivity;
import com.three.crm.bean.CommonBean;
import com.three.crm.bean.FileBean;
import com.three.crm.constant.AppConstant;
import com.three.crm.http.CommonResultCallBack;
import com.three.crm.listener.OnXpopupDismissListener;
import com.three.crm.page.VideoPlayActivity;
import com.three.crm.require.AppRequireService;
import com.three.crm.util.AppManager;
import com.three.crm.util.GsonUtils;
import com.three.crm.util.SignUtil;
import com.three.crm.util.TString;
import com.three.crm.xpopup.ReplyOrderPopup;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * 质量反馈详情
 * created by lqd on 2024-01-05.
 */
public class QualityDetailActivity extends BaseActivity {

    private int id;
    private TextView tvTitle;
    private Button btnReply;
    private EditText etCustomer,etGoodsName,etGoodsCount,etGoodsUnit,etFeedback,etRemark,etSugMoney,etFinalMoney,etXhaddress;
    private RecyclerView recyclerView;
    private NinePictureAdapter adapter;

    private ImageView ivVideo;
    private FrameLayout flVideo;
    private String uploadVideoPath = "";

    @Override
    protected void initParms(Bundle bundle) {
        if (bundle != null) {
            id = bundle.getInt(AppConstant.EXTRAS_DATA);
        }
    }

    private void handleVideo() {
        if (TextUtils.isEmpty(uploadVideoPath)) {
            flVideo.setVisibility(View.GONE);
        } else {
            flVideo.setVisibility(View.VISIBLE);
            Glide.with(this)
                    .load(uploadVideoPath)
                    .centerCrop()
                    .placeholder(R.mipmap.ic_default_image)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(ivVideo);
        }
    }

    @Override
    protected int bindLayout() {
        return R.layout.activity_quality_detail;
    }

    @Override
    protected void initViews(View view, Bundle savedInstanceState) {
        tvTitle = $(R.id.tv_title);
        tvTitle.setText(R.string.form_detail);

        etCustomer = $(R.id.et_customer);
        etGoodsName = $(R.id.et_goods_name);
        etGoodsCount = $(R.id.et_count);
        etGoodsUnit = $(R.id.et_unit);
        etRemark = $(R.id.et_remark);
        etFeedback = $(R.id.et_content);
        ivVideo = $(R.id.iv_video);
        flVideo = $(R.id.fl_video);

        etSugMoney = $(R.id.et_suggest_money);
        etFinalMoney = $(R.id.et_final_money);
        etXhaddress = $(R.id.et_xh_address);

        recyclerView = $(R.id.rv_picture);
        GridLayoutManager layoutManager = new GridLayoutManager(this,3);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new NinePictureAdapter();
        adapter.setType("detail");
        recyclerView.setAdapter(adapter);

        btnReply = $(R.id.btn_reply);
        int userType = AppManager.getLevel();
        if (userType == 1) {//地勤或者经理
            btnReply.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void setListener() {
        $(R.id.iv_left).setOnClickListener(this);
        $(R.id.fl_video).setOnClickListener(this);
        $(R.id.btn_reply).setOnClickListener(this);
    }

    @Override
    protected void widgetClick(View v) {
        switch (v.getId()){
            case R.id.iv_left:
                finish();
                break;
            case R.id.fl_video:
                onPlayVideo();
                break;
            case R.id.btn_reply:
                onShowReply();
                break;
        }
    }

    private void onShowReply() {
        if (id == 0) {
            showToast("参数异常!");
        } else {
            ReplyOrderPopup popup = new ReplyOrderPopup(this,2,id,"最终金额");
            popup.setOnXpopupDismissListener(new OnXpopupDismissListener() {
                @Override
                public void onXpopupDismiss() {
                    queryDetail();
                }
            });
            new XPopup.Builder(this)
                    .isViewMode(true)
                    .autoDismiss(true)
                    .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                    .asCustom(popup)
                    .show();
        }
    }

    private void onPlayVideo() {
        if (TextUtils.isEmpty(uploadVideoPath)) {
            showToast("视频不存在了");
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString(AppConstant.VIDEO_PATH,uploadVideoPath);
        startActivity(VideoPlayActivity.class,bundle);
    }

    @Override
    protected void initData(Context mContext) {
        queryDetail();
    }

    private void queryDetail() {
        if (id != 0) {
            showLoading(getString(R.string.loading));
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("userToken", AppManager.getToken());
                jsonObject.put("id",id);
                jsonObject.put("timestamp",getTimestamp());
                String sign = SignUtil.genSign(jsonObject);
                jsonObject.put("sign",sign);
                Log.i("TAG","jsonObject="+jsonObject.toString());
                AppRequireService.queryFormDetail(this, AppConstant.QUERY_DETAIL, jsonObject, new CommonResultCallBack(this) {
                    @Override
                    public void onResult(String result, int requireCode) {
                        hideLoading();
                        Log.i("TAG","result="+result);
                        if (requireCode == AppConstant.QUERY_DETAIL) {
                            if (!TString.isEmpty(result)) {
                                try {
                                    CommonBean bean = GsonUtils.parseJsonWithGson(result, CommonBean.class);
                                    JSONObject object = new JSONObject(result);
                                    setDetail(object,bean);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }

                    @Override
                    public void onConnectTimeOut(Call call, Exception e, int requireCode) {
                        hideLoading();
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onFail(String msg, int requireCode) {
                        hideLoading();
                        showToast(msg);
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void setDetail(JSONObject object,CommonBean bean) {
        if (bean != null) {
            etGoodsCount.setText(bean.getGoods_num());
            etGoodsName.setText(bean.getGoods_name());
            etGoodsUnit.setText(bean.getGoods_unit());
            etFeedback.setText(bean.getFeekback());
            etSugMoney.setText(bean.getSuggest_money());
            etFinalMoney.setText(bean.getFinal_money());
            etRemark.setText(bean.getNote());
            etXhaddress.setText(bean.getXh_address());
            uploadVideoPath = bean.getVideo_url();
            handleVideo();
            String imgArr = bean.getImages();
            String[] imgs = imgArr.split(",");
            if (imgs != null && imgs.length > 0) {
                List<FileBean> list = new ArrayList<>();
                for (int i = 0; i < imgs.length; i++) {
                    String url = imgs[i];
                    FileBean fileBean = new FileBean();
                    fileBean.setUrl(url);
                    list.add(fileBean);
                }
                adapter.setNewData(list);
            }
        }
        if (object != null) {
            try {
                JSONObject company = object.getJSONObject("company");
                etCustomer.setText(company.getString("title"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}